import { defineStore } from 'pinia';
import axios from 'axios';

export const useProductStore = defineStore('productStore', {
  state: () => ({
    // 商品数据
    products: [], // 当前页的商品列表
    totalProducts: 0, // 商品总数
    currentPage: 1, // 当前页码
    pageSize: 9, // 每页商品数量

    // 品牌数据
    brands: [
      {
        id: 1,
        name: '电子产品',
        children: [
          { id: 1, name: '智能手机' },
          { id: 2, name: '平板电脑' },
        ],
      },
      {
        id: 2,
        name: '家用电器',
        children: [
          { id: 3, name: '冰箱' },
          { id: 4, name: '洗衣机' },
        ],
      },
      {
        id: 3,
        name: '办公用品',
        children: [
          { id: 5, name: '打印机' },
          { id: 6, name: '扫描仪' },
        ],
      },
    ],

    // 筛选条件
    filterData: {
      brandName: '', // 一级品牌名
      subBrandName: '', // 二级品牌名
      minPrice: null, // 最低价格
      maxPrice: null, // 最高价格
    },
  }),

  getters: {
    // 筛选后的商品列表
    filteredProducts(state) {
      return state.products.filter((product) => {
        const matchesBrandName =
          !state.filterData.brandName || product.brandName === state.filterData.brandName;
        const matchesSubBrandName =
          !state.filterData.subBrandName || product.subBrandName === state.filterData.subBrandName;
        const matchesMinPrice =
          state.filterData.minPrice === null || product.averageSalePrice >= state.filterData.minPrice;
        const matchesMaxPrice =
          state.filterData.maxPrice === null || product.averageSalePrice <= state.filterData.maxPrice;

        return matchesBrandName && matchesSubBrandName && matchesMinPrice && matchesMaxPrice;
      });
    },
  },

  actions: {
    // 获取商品列表
    async fetchProducts(page = 1) {
      try {
        const response = await axios.get(`http://localhost:5123/api/products?page=${page}`);
        console.log('获取数据：', response.data);
        this.products = response.data.items; // 当前页的商品列表
        this.totalProducts = response.data.totalCount; // 商品总数
        this.currentPage = page; // 当前页码
      } catch (error) {
        console.error('获取商品列表失败:', error);
      }
    },

    // 搜索商品
    async searchProducts(keyword) {
      try {
        const response = await axios.get(`http://localhost:5123/api/products/search?keyword=${keyword}`);
        return response.data;
      } catch (error) {
        console.error('搜索商品失败:', error);
      }
    },

    // 添加商品
    async addProduct(productData) {
      try {
        const formData = new FormData();
        for (const key in productData) {
          formData.append(key, productData[key]);
        }
        await axios.post('http://localhost:5123/api/products', formData);
        this.fetchProducts(this.currentPage); // 刷新当前页商品
      } catch (error) {
        console.error('添加商品失败:', error);
      }
    },

    // 删除商品
    async deleteProduct(productId) {
      try {
        await axios.delete(`http://localhost:5123/api/products/${productId}`);
        this.fetchProducts(this.currentPage); // 刷新当前页商品
      } catch (error) {
        console.error('删除商品失败:', error);
      }
    },

    // 更新商品
    async updateProduct(productId, productData) {
      try {
        console.log('更新商品的数据：', productData);
        await axios.put(`http://localhost:5123/api/products`, productData, {
          headers: {
            'Content-Type': 'application/json',
          },
        });
        this.fetchProducts(this.currentPage); // 刷新当前页商品
      } catch (error) {
        console.error('更新商品失败:', error);
      }
    },

    // 更新筛选条件
    updateFilter(filter) {
      this.filterData = filter;
    },
  },
});